package org.opens.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.opens.dto.StartProcessDto;
import org.opens.service.FlowableService;
import org.opens.vo.TaskVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FlowableServiceImpl implements FlowableService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Override
    @Transactional
    public String startProcess(StartProcessDto startProcessDto) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(startProcessDto.getProcessDefineKey(), startProcessDto.getValues());
        return processInstance.getProcessInstanceId();
    }

    @Override
    public List<TaskVo> getTasksByAssign(String assignee) {
        List<Task> taskList = taskService.createTaskQuery().taskAssignee(assignee).list();
        if (CollectionUtil.isEmpty(taskList)) {
            return null;
        }

        List<TaskVo> result = new ArrayList<>();
        for (Task taskItem : taskList) {
            TaskVo taskVo = new TaskVo();
            taskVo.setId(taskItem.getId());
            taskVo.setName(taskItem.getName());
            result.add(taskVo);
        }
        return result;
    }
}
